package com.ruoyi.system.service.impl;

import com.ruoyi.system.mapper.AgoniMessageMapper;
import com.ruoyi.system.mapper.AgoniUserMapper;
import com.ruoyi.system.pojo.dto.MessageUserDTO;
import com.ruoyi.system.pojo.dto.SendMessageDataDTO;
import com.ruoyi.system.pojo.entity.User;
import com.ruoyi.system.pojo.entity.UserMessage;
import com.ruoyi.system.pojo.util.Pair;
import com.ruoyi.system.pojo.vo.MessageUserVO;
import com.ruoyi.system.pojo.vo.UserChatVO;
import com.ruoyi.system.service.IAgoniMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.Size;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class IAgoniMessageServiceImpl implements IAgoniMessageService {
    @Autowired
    private AgoniMessageMapper agoniMessageMapper;

    @Autowired
    private AgoniUserMapper agoniUserMapper;



    /**
     * 获取私信用户消息列表
     * @param userId 用户id
     */

    @Override
    public List<MessageUserVO> getMessageUserListBytoken(Long userId) {

        /**
         * 1：根据用户id查询私信消息列表，即查询接收者，或者发信人为当前用户的消息
         * 2：对接收者和发信人一样或者相反的消息进行分组，并按时间排序，对每一组统计未读消息数量
         * 3：获取最新一条记录消息，并判断是否已读，
         */

        List<UserMessage> messageList = agoniMessageMapper.getMessageList(userId);
        log.info("messageList:{}", messageList);

        // 步骤1：按发送者和接收者分组
        Map<Pair, List<UserMessage>> groups = new HashMap<>();
        for (UserMessage msg : messageList) {
            Pair key = new Pair(msg.getSenderId(), msg.getReceiverId());
            groups.computeIfAbsent(key, k -> new ArrayList<>()).add(msg);
        }

        // 步骤2：处理每组消息并生成VO
        List<MessageUserVO> dialogGroups = new ArrayList<>();
        for (Map.Entry<Pair, List<UserMessage>> entry : groups.entrySet()) {
            Pair pair = entry.getKey();
            List<UserMessage> messages = entry.getValue();

            // 按时间降序、ID降序排序
            messages.sort((m1, m2) -> {
                int timeCompare = m2.getSendTime().compareTo(m1.getSendTime());
                if (timeCompare != 0) {
                    return timeCompare;
                } else {
                    return Long.compare(m2.getId(), m1.getId());
                }
            });

            // 统计未读消息数（仅统计当前用户作为接收者且isRead=0的消息）
            int unreadCount = 0;
            for (UserMessage msg : messages) {
                if (msg.getReceiverId().equals(userId) && msg.getIsRead() == 0) {
                    unreadCount++;
                }
            }

            // 获取最新消息内容和时间
            UserMessage latestMsg = messages.isEmpty() ? null : messages.get(0);
            String latestContent = latestMsg != null ? latestMsg.getContent() : "";
            Date latestTime = latestMsg != null ? latestMsg.getSendTime() : new Date();

            // 获取发送者和接收者的用户信息
            User senderUser = agoniUserMapper.selectByUserId(userId);
            Long user2=null;
            if (userId.equals(pair.getFirst())){
               user2= pair.getSecond();
            }else{
                user2= pair.getFirst();
            }
            User receiverUser=agoniUserMapper.selectByUserId(user2);


            // 封装为MessageUserVO
            MessageUserVO vo = new MessageUserVO();
            vo.setSenderId(userId);
            if(userId.equals(pair.getFirst())){
                vo.setReceiverId(pair.getSecond());
            }else{
                vo.setReceiverId(pair.getFirst());
            }

            vo.setSenderName(senderUser.getUsername());
            vo.setReceiverName(receiverUser.getUsername());
            vo.setSenderAvatar(senderUser.getAvatar());
            vo.setReceiverAvatar(receiverUser.getAvatar());
            vo.setMessageUnreadCount(unreadCount);
            vo.setLatestMessageContent(latestContent);
            vo.setLatestMessageTime(latestTime);

            dialogGroups.add(vo);
        }
        return dialogGroups;
    }



    //获取与某个用户的消息列表
    private UserChatVO convertToUserChatVO(UserMessage msg) {
        User user1=agoniUserMapper.selectByUserId(msg.getSenderId());
        User user2=agoniUserMapper.selectByUserId(msg.getReceiverId());

        UserChatVO vo = new UserChatVO();
        vo.setSenderId(msg.getSenderId());
        vo.setReceiverId(msg.getReceiverId());
        vo.setSenderName(user1.getUsername());
        vo.setReceiverName(user2.getUsername());
        vo.setSenderAvatar(user1.getAvatar());
        vo.setReceiverAvatar(user2.getAvatar());
        vo.setMessageContent(msg.getContent());
        vo.setMessageTime(msg.getSendTime());
        return vo;
    }
    @Override
    public List<UserChatVO> getChatList(MessageUserDTO messageUserDTO) {
        Long currentUserId = messageUserDTO.getSenderId();
        Long targetUserId = messageUserDTO.getReceiverId();

        // 构建对话组键
        Pair conversationKey = new Pair(currentUserId, targetUserId);

        // 查询该对话组的全部消息
        List<UserMessage> messages = agoniMessageMapper.selectMessagesByConversation(conversationKey);

        if (messages.isEmpty()) {
            return Collections.emptyList();
        }
        // 按时间升序排序
        messages.sort((m1, m2) -> {
            int timeCompare = m1.getSendTime().compareTo(m2.getSendTime()); // 按时间升序比较
            if (timeCompare != 0) {
                return timeCompare; // 如果时间不同，返回时间比较结果
            } else {
                return Long.compare(m2.getId(), m1.getId()); // 如果时间相同，按 ID 降序比较
            }
        });
        // 批量标记消息为已读（当前用户作为接收者的消息）
        List<Long> messageIdsToMarkRead = messages.stream()
                .filter(msg -> msg.getReceiverId().equals(currentUserId))
                .map(UserMessage::getId)
                .collect(Collectors.toList());

        if (!messageIdsToMarkRead.isEmpty()) {
            agoniMessageMapper.updateIsRead(messageIdsToMarkRead, true);
        }

        // 封装为VO列表
        return messages.stream()
                .map(this::convertToUserChatVO)
                .collect(Collectors.toList());
    }



    //发送消息

    @Override
    public Boolean sendMessage(SendMessageDataDTO sendMessageDataDTO) {
        UserMessage message = new UserMessage();
        message.setSenderId(sendMessageDataDTO.getSenderId());
        message.setReceiverId(sendMessageDataDTO.getReceiverId());
        message.setContent(sendMessageDataDTO.getMessageContent());
        message.setSendTime(new Date());
        message.setIsRead(0);
        message.setMessageType(1);
        int result = agoniMessageMapper.insertMessage(message);
        if (result > 0) {
            return true;
        } else {
            return false;
        }
    }
}
